package com.hsogoo.avatar.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

import com.hsogoo.avatar.constants.AvatarConstant;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/10/17.
 */
@Slf4j
public class ConfigUtil {

    private static class ConfigUtilHolder{
        private static final ConfigUtil instance = new ConfigUtil();
    }
    private ConfigUtil(){

    }

    public synchronized static ConfigUtil getInstance(){
        return ConfigUtilHolder.instance;
    }

    /**
     * 加载/META-INF/app.properties中的配置项
     * @return
     */
    public Properties loadAppProperties(){
        Properties appProperties = new Properties();
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(AvatarConstant.APP_PROPERTIES_CLASSPATH);
            if (inputStream == null) {
                inputStream = getClass().getResourceAsStream(AvatarConstant.APP_PROPERTIES_CLASSPATH);
            }

            if (inputStream == null) {
                log.warn("{} not found from classpath!", AvatarConstant.APP_PROPERTIES_CLASSPATH);
                return appProperties;
            }

            try {
                appProperties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            } finally {
                inputStream.close();
            }
        } catch (Throwable ex) {
            log.error("Initialize DefaultApplicationProvider failed.", ex);
        }
        return appProperties;
    }

    public String getDefaultRegistryAddress(){
        //-Davatar.registry.url=127.0.0.1:2181
        String registryUrl = System.getProperty("avatar.registry.url");
        if(StringUtils.isBlank(registryUrl)){
            registryUrl = loadAppProperties().getProperty("avatar.registry.url");
        }
        return registryUrl;
    }

    public int getAvatarPort(){
        //-Davatar.server.port=22880
        String port = System.getProperty("avatar.server.port");
        if(StringUtils.isBlank(port)){
            port = loadAppProperties().getProperty("avatar.server.port");
        }
        if(StringUtils.isNotBlank(port)){
            return Integer.parseInt(port);
        }
        return AvatarConstant.AVATAR_DEFAULT_PORT;
    }

    public String getAppName(){
        String appName = loadAppProperties().getProperty("app.name");
        if(StringUtils.isBlank(appName)){
            appName = AvatarConstant.UNKNOWN_APP_NAME;
        }
        return appName;
    }
}
